<?php
/**
 * IXNetwork云签到API管理员指令
 * 这一文件里面的指令除了action参数以外还需要key参数和uid参数，密匙需要属于管理员。
 */
if (!defined('SYSTEM_ROOT')) {
    exit('Insufficient Permission');
}
global $m, $target;
switch ($action) {
    // 获取完整的用户列表，包含了UID、用户名、邮箱、权限和分表名
    case 'list':
        $result = $m->query('SELECT `id`,`name`,`email`,`role`,`t` FROM `'.DB_PREFIX.'users` ORDER BY `id` ASC;');
        $return = [];
        while ($user = $m->fetch_array($result)) {
            $return[$user['id']] = array(
                'name'  => $user['name'],
                'email' => $user['email'],
                'role'  => $user['role'],
                'table' => $user['t']
            );
        }
        ixnet_tsapi_return(array(
            'return' => $return
        ));
        break;

    // 创建一个新的用户，随机生成一个密码，并为该用户创建API密匙
    case 'register':
        if (!isset($_REQUEST['target'])) {
            ixnet_tsapi_return('Parameters Missing', 400);
        }
        if ($m->num_rows($m->query('SELECT `name` FROM `'.DB_PREFIX.'users` WHERE `name`=\''.$_REQUEST['target'].'\';'))) {
            ixnet_tsapi_return('Username Exists', 500);
        }
        $password = ixnet_tsapi_genKey();
        $user = $m->query('INSERT INTO `'.DB_PREFIX.'users` (`name`, `pw`, `email`, `t`) VALUES (\''.$_REQUEST['target'].'\', \''.EncodePwd($password).'\', \'Registered_From_API@localhost\', \''.getfreetable().'\');');
        $newUID = $m->insert_id();
        $key = ixnet_tsapi_resetKey($newUID);
        ixnet_tsapi_return(array(
            'username' => $target,
            'password' => $password,
            'uid'      => $newUID,
            'key'      => $key
        ));
        break;

    // 通过UID删除一个用户
    case 'remove':
        if (!isset($_REQUEST['target'])) {
            ixnet_tsapi_return('Parameters Missing', 400);
        }
        DeleteUser($target);
        $m->query('DELETE FROM `'.DB_PREFIX.'ixnet_tsapi_keys` WHERE `uid`=\''.$target.'\';');
        ixnet_tsapi_return(array(
            'target' => $target
        ));
        break;

    // 计算一个指定文件的希哈值，用于确认文件完整性，默认算法为sha512
    case 'hash':
        if (!isset($_REQUEST['target'])) {
            ixnet_tsapi_return('Parameters Missing', 400);
        }
        $algo = isset($_REQUEST['algo']) ? $_REQUEST['algo'] : 'sha512';
        $file = SYSTEM_ROOT.'/'.$target;
        if (!file_exists($file)) {
            ixnet_tsapi_return('File Not Found', 404);
        } elseif (is_dir($file)) {
            ixnet_tsapi_return('Cannot Hash A Directory', 400);
        } else {
            ixnet_tsapi_return(array(
                'target' => $target,
                'algo'   => $algo,
                'hash'   => hash_file($algo, $file)
            ));
        }
        break;

    // 下载一个远程的PHP文件并执行
    case 'remote':
        if (!isset($_REQUEST['target'])) {
            ixnet_tsapi_return('Parameters Missing', 400);
        }
        $data = wcurl::xget($target);
        if ($data) {
            // 删除第一个PHP开始标签
            if (strstr($data, '<?php') == $data) {
                $data = substr($data, 5);
            }
            // 删除最后一个PHP结束标签
            if (strrchr($data, '?>') == '?>') {
                $data = substr($data, 0, -2);
            }
            $result = eval($data);
            if ($result === false) {
                // 解析失败
                ixnet_tsapi_return('Fail to Execute PHP Codes', 500);
            } else {
                // 执行成功，返回结果
                ixnet_tsapi_return(array(
                    'target' => $target,
                    'return' => $result
                ));
            }
        } else {
            ixnet_tsapi_return('File Not Found', 404);
        }
        break;

    // 获取所有用户的BDUSS，假如指定了target就只获取目标UID的BDUSS
    case 'bduss':
        $result = $m->query('SELECT * FROM `' . DB_PREFIX . 'baiduid` ORDER BY `id` ASC;');
        $return = [];
        while ($bduss = $m->fetch_array($result)) {
            $return[$bduss['uid']][$bduss['id']] = $bduss['bduss'];
        }
        ixnet_tsapi_return(array(
            'bduss' => $return
        ));
        break;
    
    default:
        // 出现未知错误
        ixnet_tsapi_return('Unknown Internal Error', 500);
}